<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>干支体质配置编辑器</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .selector-group {
            display: flex;
            gap: 20px;
            margin-bottom: 30px;
            align-items: center;
        }
        .selector {
            flex: 1;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        select {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            background-color: white;
        }
        select:focus {
            border-color: #4CAF50;
            outline: none;
        }
        .selected-gz {
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            color: #4CAF50;
            margin: 20px 0;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }
        .data-display {
            margin-top: 30px;
        }
        .data-section {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            border-left: 4px solid #4CAF50;
        }
        .data-section h3 {
            margin-top: 0;
            color: #333;
        }
        .data-section ul {
            margin: 10px 0;
            padding-left: 20px;
        }
        .data-section li {
            margin-bottom: 5px;
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
        }
        .edit-form {
            margin-top: 20px;
        }
        .edit-form input[type="text"] {
            width: 100%;
            padding: 8px;
            margin: 4px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .edit-form .form-section {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            border-left: 4px solid #4CAF50;
        }
        .edit-form .form-section h3 {
            margin-top: 0;
            color: #333;
        }
        .edit-form .add-item-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 10px 0;
        }
        .edit-form .add-item-btn:hover {
            background-color: #45a049;
        }
        .edit-form .remove-item-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }
        .edit-form .remove-item-btn:hover {
            background-color: #da190b;
        }
        .edit-form .submit-btn {
            background-color: #2196F3;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        .edit-form .submit-btn:hover {
            background-color: #0b7dda;
        }
        .edit-form .acupoint-item {
            margin-bottom: 15px;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    {% if session.get('logged_in') %}
    <div style="background-color: #f0f0f0; padding: 10px; text-align: right;">
        已登录用户: {{ session.get('username') }} | <a href="/logout">退出</a>
    </div>
    {% endif %}
    <div class="container">
        <h1>干支体质配置编辑器</h1>
        
        <div class="selector-group">
            <div class="selector">
                <label for="tiangan">天干：</label>
                <select id="tiangan" onchange="updateDizhiOptions(); sendGzData();">
                    <option value="甲">甲 (阳)</option>
                    <option value="乙">乙 (阴)</option>
                    <option value="丙">丙 (阳)</option>
                    <option value="丁">丁 (阴)</option>
                    <option value="戊">戊 (阳)</option>
                    <option value="己">己 (阴)</option>
                    <option value="庚">庚 (阳)</option>
                    <option value="辛">辛 (阴)</option>
                    <option value="壬">壬 (阳)</option>
                    <option value="癸">癸 (阴)</option>
                </select>
            </div>
            
            <div class="selector">
                <label for="dizhi">地支：</label>
                <select id="dizhi" onchange="sendGzData()">
                    <!-- 地支选项将通过JavaScript动态生成 -->
                </select>
            </div>
        </div>

        <div class="selected-gz" id="selected-gz">
            当前选择：甲子
        </div>

        <div class="data-display" id="data-display">
            <div class="loading">请选择干支组合查看详情...</div>
        </div>
    </div>

    <script>
        // 天干地支的阴阳属性
        const yinyangMap = {
            // 天干阴阳
            '甲': '阳', '乙': '阴', '丙': '阳', '丁': '阴', '戊': '阳',
            '己': '阴', '庚': '阳', '辛': '阴', '壬': '阳', '癸': '阴',
            
            // 地支阴阳
            '子': '阳', '丑': '阴', '寅': '阳', '卯': '阴', '辰': '阳',
            '巳': '阴', '午': '阳', '未': '阴', '申': '阳', '酉': '阴',
            '戌': '阳', '亥': '阴'
        };

        // 所有地支
        const allDizhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            // 设置默认选项
            document.getElementById('tiangan').value = '甲';
            updateDizhiOptions();
            document.getElementById('dizhi').value = '子';
            
            // 初始发送数据
            sendGzData();
        });

        // 更新地支选项
        function updateDizhiOptions() {
            const tiangan = document.getElementById('tiangan').value;
            const dizhiSelect = document.getElementById('dizhi');
            const currentYinyang = yinyangMap[tiangan];
            
            // 清空现有选项
            dizhiSelect.innerHTML = '';
            
            // 根据天干的阴阳属性过滤地支
            allDizhi.forEach(dizhi => {
                if (yinyangMap[dizhi] === currentYinyang) {
                    const option = document.createElement('option');
                    option.value = dizhi;
                    option.textContent = `${dizhi} (${yinyangMap[dizhi]})`;
                    dizhiSelect.appendChild(option);
                }
            });
            
            // 更新显示的干支
            updateSelectedGzDisplay();
        }

        // 更新显示的干支组合
        function updateSelectedGzDisplay() {
            const tiangan = document.getElementById('tiangan').value;
            const dizhi = document.getElementById('dizhi').value;
            document.getElementById('selected-gz').textContent = `当前选择：${tiangan}${dizhi}`;
        }

        // 向后端发送干支数据
        function sendGzData() {
            updateSelectedGzDisplay();
            
            const tiangan = document.getElementById('tiangan').value;
            const dizhi = document.getElementById('dizhi').value;
            const ganzhi = tiangan + dizhi;
            
            // 显示加载状态
            const dataDisplay = document.getElementById('data-display');
            dataDisplay.innerHTML = '<div class="loading">正在加载数据...</div>';
            
            // 向后端发送AJAX请求
            fetch('/get_gz_table', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ ganzhi: ganzhi })
            })
            .then(response => response.json())
            .then(data => {
                if (data.res === 'ok') {
                    console.log('ganzhi data:',data.data);
                    displayGzData(data.data);
                } else {
                    // 如果后端未实现，使用模拟数据
                    console.log('后端未返回数据，使用模拟数据');
                    displayGzData(ganzhi);
                }
            })
            .catch(error => {
                console.error('请求错误:', error);
                // 出错时使用模拟数据
                displayGzData(ganzhi);
            });
        }

        // 添加项目
        function addItem(containerId, placeholder) {
            const container = document.getElementById(containerId);
            const itemCount = container.querySelectorAll('div').length;
            const newItem = document.createElement('div');
            newItem.innerHTML = `
                <input type="text" name="${containerId}_${itemCount}" value="" placeholder="${placeholder}">
                <button type="button" class="remove-item-btn" onclick="removeItem('${containerId}', this)">删除</button>
            `;
            container.appendChild(newItem);
        }

        // 删除项目
        function removeItem(containerId, button) {
            const item = button.parentElement;
            item.remove();
        }

        // 添加穴位
        function addAcupoint() {
            const container = document.getElementById('acupoint-inputs');
            const acupointCount = container.querySelectorAll('.acupoint-item').length;
            const newAcupoint = document.createElement('div');
            newAcupoint.className = 'acupoint-item';
            newAcupoint.innerHTML = `
                <h5>穴位 ${acupointCount + 1}</h5>
                <div>
                    <label>名称：</label>
                    <input type="text" name="acupoint_name_${acupointCount}" value="" placeholder="穴位名称">
                </div>
                <div>
                    <label>功效：</label>
                    <div id="acupoint-effect-${acupointCount}">
                        <div>
                            <input type="text" name="acupoint_effect_${acupointCount}_0" value="" placeholder="功效描述">
                            <button type="button" class="remove-item-btn" onclick="removeItem('acupoint-effect-${acupointCount}', this)">删除</button>
                        </div>
                    </div>
                    <button type="button" class="add-item-btn" onclick="addItem('acupoint-effect-${acupointCount}', '功效描述')">添加功效</button>
                </div>
                <button type="button" class="remove-item-btn" onclick="removeAcupoint(${acupointCount})">删除穴位</button>
            `;
            container.appendChild(newAcupoint);
        }

        // 删除穴位
        function removeAcupoint(index) {
            const acupoints = document.querySelectorAll('.acupoint-item');
            if (acupoints[index]) {
                acupoints[index].remove();
            }
        }

        // 提交表单
        function submitForm() {
            const tiangan = document.getElementById('tiangan').value;
            const dizhi = document.getElementById('dizhi').value;
            const ganzhi = tiangan + dizhi;
            
            // 收集表单数据
            const formData = {
                '病机核心': collectInputValues('bingji-inputs'),
                '体质': {
                    '体型': collectInputValues('tixing-inputs'),
                    '面色': collectInputValues('mianse-inputs'),
                    '功能倾向': collectInputValues('gongneng-inputs'),
                    '心理': {
                        '优势': collectInputValues('xinli-youshi-inputs'),
                        '劣势': collectInputValues('xinli-lieshi-inputs')
                    }
                },
                '敏感脏腑': collectInputValues('zangfu-inputs'),
                '易感疾病': collectInputValues('jibing-inputs'),
                '调理方案': {
                    '饮食': collectInputValues('yinshi-inputs'),
                    '保养穴位': collectAcupointData()
                }
            };

            // 过滤空值
            const filteredData = filterEmptyValues(formData);
            
            console.log('提交的数据:', filteredData);
            
            // 向后端发送数据
            fetch('/update_gz_table', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    ganzhi: ganzhi,
                    data: filteredData
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.res === 'ok') {
                    alert('数据保存成功！');
                } else {
                    alert('保存失败：' + (data.msg || '未知错误'));
                }
            })
            .catch(error => {
                console.error('保存错误:', error);
                alert('保存失败，请检查网络连接');
            });
        }

        // 收集输入框的值
        function collectInputValues(containerId) {
            const container = document.getElementById(containerId);
            if (!container) return [];
            
            const inputs = container.querySelectorAll('input[type="text"]');
            const values = Array.from(inputs).map(input => input.value.trim()).filter(value => value !== '');
            return values.length > 0 ? values : ['请输入内容'];
        }

        // 收集穴位数据
        function collectAcupointData() {
            const acupoints = document.querySelectorAll('.acupoint-item');
            const acupointData = [];
            
            acupoints.forEach((acupoint, index) => {
                const nameInput = acupoint.querySelector(`input[name="acupoint_name_${index}"]`);
                const effectContainer = document.getElementById(`acupoint-effect-${index}`);
                
                if (nameInput && effectContainer) {
                    const name = nameInput.value.trim();
                    const effectInputs = effectContainer.querySelectorAll('input[type="text"]');
                    const effects = Array.from(effectInputs).map(input => input.value.trim()).filter(effect => effect !== '');
                    
                    if (name || effects.length > 0) {
                        acupointData.push({
                            '名称': name || '请输入穴位名称',
                            '功效': effects.length > 0 ? effects : ['请输入功效描述']
                        });
                    }
                }
            });
            
            return acupointData.length > 0 ? acupointData : [{
                '名称': '请输入穴位名称',
                '功效': ['请输入功效描述']
            }];
        }

        // 过滤空值
        function filterEmptyValues(data) {
            const filtered = JSON.parse(JSON.stringify(data));
            
            // 过滤数组空值
            function filterArray(arr) {
                return arr.filter(item => {
                    if (typeof item === 'string') {
                        return item !== '请输入内容' && item !== '';
                    }
                    return true;
                });
            }
            
            // 递归过滤
            function recursiveFilter(obj) {
                for (const key in obj) {
                    if (Array.isArray(obj[key])) {
                        obj[key] = filterArray(obj[key]);
                        if (obj[key].length === 0) {
                            obj[key] = ['请输入内容'];
                        }
                    } else if (typeof obj[key] === 'object' && obj[key] !== null) {
                        recursiveFilter(obj[key]);
                    }
                }
            }
            
            recursiveFilter(filtered);
            return filtered;
        }

        // 显示干支数据（可编辑表单）
        function displayGzData(data) {
            const dataDisplay = document.getElementById('data-display');
            
            // 如果后端返回的是字符串（模拟数据），使用默认数据
            let gzData;
            if (typeof data === 'string') {
                gzData = {
                    '病机核心': ['请输入病机核心内容'],
                    '体质': {
                        '体型': ['请输入体型描述'],
                        '面色': ['请输入面色描述'],
                        '功能倾向': ['请输入功能倾向描述'],
                        '心理': {
                            '优势': ['请输入心理优势'],
                            '劣势': ['请输入心理劣势']
                        }
                    },
                    '敏感脏腑': ['请输入敏感脏腑'],
                    '易感疾病': ['请输入易感疾病'],
                    '调理方案': {
                        '饮食': ['请输入饮食建议'],
                        '保养穴位': [
                            {
                                '名称': '请输入穴位名称',
                                '功效': ['请输入功效描述']
                            }
                        ]
                    }
                };
            } else {
                gzData = data;
            }
            
            let html = `
                <form id="edit-form" class="edit-form">
                    <div class="form-section">
                        <h3>病机核心</h3>
                        <div id="bingji-inputs">
                            ${gzData['病机核心'].map((item, index) => `
                                <div>
                                    <input type="text" name="bingji_${index}" value="${item}" placeholder="病机核心内容">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('bingji-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('bingji-inputs', '病机核心内容')">添加病机核心</button>
                    </div>

                    <div class="form-section">
                        <h3>体质</h3>
                        
                        <h4>体型</h4>
                        <div id="tixing-inputs">
                            ${gzData['体质']['体型'].map((item, index) => `
                                <div>
                                    <input type="text" name="tixing_${index}" value="${item}" placeholder="体型描述">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('tixing-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('tixing-inputs', '体型描述')">添加体型描述</button>
                        
                        <h4>面色</h4>
                        <div id="mianse-inputs">
                            ${gzData['体质']['面色'].map((item, index) => `
                                <div>
                                    <input type="text" name="mianse_${index}" value="${item}" placeholder="面色描述">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('mianse-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('mianse-inputs', '面色描述')">添加面色描述</button>
                        
                        <h4>功能倾向</h4>
                        <div id="gongneng-inputs">
                            ${gzData['体质']['功能倾向'].map((item, index) => `
                                <div>
                                    <input type="text" name="gongneng_${index}" value="${item}" placeholder="功能倾向描述">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('gongneng-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('gongneng-inputs', '功能倾向描述')">添加功能倾向</button>
                        
                        <h4>心理</h4>
                        <h5>优势</h5>
                        <div id="xinli-youshi-inputs">
                            ${gzData['体质']['心理']['优势'].map((item, index) => `
                                <div>
                                    <input type="text" name="xinli_youshi_${index}" value="${item}" placeholder="心理优势">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('xinli-youshi-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('xinli-youshi-inputs', '心理优势')">添加心理优势</button>
                        
                        <h5>劣势</h5>
                        <div id="xinli-lieshi-inputs">
                            ${gzData['体质']['心理']['劣势'].map((item, index) => `
                                <div>
                                    <input type="text" name="xinli_lieshi_${index}" value="${item}" placeholder="心理劣势">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('xinli-lieshi-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('xinli-lieshi-inputs', '心理劣势')">添加心理劣势</button>
                    </div>

                    <div class="form-section">
                        <h3>敏感脏腑</h3>
                        <div id="zangfu-inputs">
                            ${gzData['敏感脏腑'].map((item, index) => `
                                <div>
                                    <input type="text" name="zangfu_${index}" value="${item}" placeholder="敏感脏腑">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('zangfu-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('zangfu-inputs', '敏感脏腑')">添加敏感脏腑</button>
                    </div>

                    <div class="form-section">
                        <h3>易感疾病</h3>
                        <div id="jibing-inputs">
                            ${gzData['易感疾病'].map((item, index) => `
                                <div>
                                    <input type="text" name="jibing_${index}" value="${item}" placeholder="易感疾病">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('jibing-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('jibing-inputs', '易感疾病')">添加易感疾病</button>
                    </div>

                    <div class="form-section">
                        <h3>调理方案</h3>
                        
                        <h4>饮食</h4>
                        <div id="yinshi-inputs">
                            ${gzData['调理方案']['饮食'].map((item, index) => `
                                <div>
                                    <input type="text" name="yinshi_${index}" value="${item}" placeholder="饮食建议">
                                    <button type="button" class="remove-item-btn" onclick="removeItem('yinshi-inputs', this)">删除</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addItem('yinshi-inputs', '饮食建议')">添加饮食建议</button>
                        
                        <h4>保养穴位</h4>
                        <div id="acupoint-inputs">
                            ${gzData['调理方案']['保养穴位'].map((acupoint, index) => `
                                <div class="acupoint-item">
                                    <h5>穴位 ${index + 1}</h5>
                                    <div>
                                        <label>名称：</label>
                                        <input type="text" name="acupoint_name_${index}" value="${acupoint['名称']}" placeholder="穴位名称">
                                    </div>
                                    <div>
                                        <label>功效：</label>
                                        <div id="acupoint-effect-${index}">
                                            ${acupoint['功效'].map((effect, effectIndex) => `
                                                <div>
                                                    <input type="text" name="acupoint_effect_${index}_${effectIndex}" value="${effect}" placeholder="功效描述">
                                                    <button type="button" class="remove-item-btn" onclick="removeItem('acupoint-effect-${index}', this)">删除</button>
                                                </div>
                                            `).join('')}
                                        </div>
                                        <button type="button" class="add-item-btn" onclick="addItem('acupoint-effect-${index}', '功效描述')">添加功效</button>
                                    </div>
                                    <button type="button" class="remove-item-btn" onclick="removeAcupoint(${index})">删除穴位</button>
                                </div>
                            `).join('')}
                        </div>
                        <button type="button" class="add-item-btn" onclick="addAcupoint()">添加穴位</button>
                    </div>

                    <button type="button" class="submit-btn" onclick="submitForm()">提交修改</button>
                </form>
            `;
            
            dataDisplay.innerHTML = html;
        }
    </script>
</body>
</html>
